std::move

From Cppreference

Jump to: navigation, search
Defined in header <utility>

template <class T>
typename std::remove_reference<T>::type&& move(T&& t);
(C++11 feature)

Obtains an rvalue reference to its argument, typically used to implement move semantics when invoking functions; that is, the function overload that takes rvalue references will be selected, and the contents of t will be moved into the function, leaving t as an xvalue.

Contents

[edit] Parameters

t - the object to be moved

[edit] Return value

static_cast<typename std::remove_reference<T>::type&&>(t)

[edit] Exceptions

noexcept specification:  
noexcept

  (C++11 feature)

[edit] Example

#include <iostream>
#include <utility>
#include <vector>
#include <string>
int main()
{
    std::string str = "Hello";
    std::vector<std::string> v;
    v.push_back(str); // uses the push_back(const T&) overload
    std::cout << "After copy, str is \"" << str << "\"\n";
    v.push_back(std::move(str)); // uses the push_back(T&&) overload
    std::cout << "After move, str is \"" << str << "\"\n";
    std::cout << "The contents of the vector are \"" << v[0]
                                         << "\", \"" << v[1] << "\"\n";
}

Output:

After copy, str is "Hello"
After move, str is ""
The contents of the vector are "Hello", "Hello"

[edit] Complexity

constant

[edit] See also

forward (C++11)
forwards a function argument
(function template)
move_if_noexcept (C++11)
obtains an rvalue reference if the move constructor does not throw
(function template)
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox
In other languages